package com.xxxx.seckill.utils;



import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.vo.RespBean;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 生成用户工具类
 *
 * ：用于添加批量的测试数据 < 纯jdbc >
 *
 * @author: heyanfeng
 * @date 2022/3/4 3:29 下午
 * @ClassName: UserUtil
 */
public class UserUtil {
    private static void createUser( int count) throws Exception {
         List<User> users = new ArrayList<>(count);
        // 生成用户
        for (int i = 0 ; i < count ;i++ ){
            User user = new User();
            user.setId(13000000000L+i);
            user.setNickname( "user"+i);
            user.setSalt( "1a2b3c");
            user.setPassword(MD5Util.inputPassToDBPass( "123456",user.getSalt()));
            user.setLoginCount(1);
            user.setRegisterDate(new Date());
            users.add(user);
        }
        System.out.println("create user");

//        //插入数据库
//            //1、获取连接
//        Connection connection = getConn();
//            //2、编写sql语句
//        String sql = "insert into t_user(login_count,nickname,register_date,salt,password,id) values(?,?,?,?,?,?)";
//            //3、占位符填充
//        PreparedStatement preparedStatement = connection.prepareStatement(sql);
//        for (int i  = 0 ;i< users.size();i++){
//            User user = users.get(i);
//            preparedStatement.setInt(1,user.getLoginCount());
//            preparedStatement.setString(2, user.getNickname());
//            preparedStatement.setTimestamp(3,new Timestamp(user.getRegisterDate().getTime()));
//            preparedStatement.setString(4, user.getSalt());
//            preparedStatement.setString(5, user.getPassword());
//            preparedStatement.setLong(6,user.getId());
//            preparedStatement.addBatch();
//        }
//            //4、添加批量
//        preparedStatement.executeBatch();
//        preparedStatement.close();
//        connection.close();
//        System.out.println("insert to db");

        //登录，生成token
        String urlString = "http://localhost:8080/login/doLogin";
        //保存到本地
        File file = new File( "D:\\Users\\ASUS\\Desktop\\config.txt");
        if (file.exists()){
            file.delete();
        }
        RandomAccessFile raf = new RandomAccessFile(file,"rw");
        file.createNewFile();
        raf.seek(0);
        for(int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            URL url = new URL(urlString);
            //请求接口
            HttpURLConnection co = (HttpURLConnection) url.openConnection();
            co.setRequestMethod("POST");
            co.setDoOutput(true);
            OutputStream out = co.getOutputStream();
            String params = "mobile=" + user.getId() + "&password=" +MD5Util.inputPassToFromPass("123456");
            out.write(params.getBytes());
            out.flush();
            InputStream inputStream = co.getInputStream();
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buff))>=0){
                bout.write(buff, 0,len) ;
            }
            inputStream.close();
            bout.close();
            String response = new String(bout.toByteArray());
            ObjectMapper mapper = new ObjectMapper();
            RespBean respBean = mapper.readValue(response,RespBean.class);
            String userTicket = ((String) respBean.getMessage());
            System.out.println("create userTicket :" + user.getId());

            String row = user.getId() + "," + userTicket;
            raf.seek(raf.length());
            raf.write(row.getBytes());
            raf.write("\r\n".getBytes());
            System.out.println( "write to file :" + user.getId());
        }
        raf.close();
        System.out.println("over");
    }

    private static Connection getConn() throws Exception {
        String url = "jdbc:mysql://localhost:3306/seckill?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
        String username = "root" ;
        String password = "123456";
        String driver = "com.mysql.cj.jdbc.Driver";
        Class.forName(driver);
        return DriverManager.getConnection(url,username,password);
    }

    public static void main(String[] args) throws Exception {
         createUser(5000);
    }
}
